summaryrefslogtreecommitdiffstats
path: root/src/core/hle/kernel/k_thread.h
blob: f4cb861a9c7dd7f7a1d4d2e8ebb3b090f15b4b1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <array>
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <span>
#include <string>
#include <utility>
#include <vector>

#include <boost/intrusive/list.hpp>

#include "common/common_types.h"
#include "common/intrusive_red_black_tree.h"
#include "common/spin_lock.h"
#include "core/arm/arm_interface.h"
#include "core/hle/kernel/k_affinity_mask.h"
#include "core/hle/kernel/k_light_lock.h"
#include "core/hle/kernel/k_spin_lock.h"
#include "core/hle/kernel/k_synchronization_object.h"
#include "core/hle/kernel/k_timer_task.h"
#include "core/hle/kernel/k_worker_task.h"
#include "core/hle/kernel/slab_helpers.h"
#include "core/hle/kernel/svc_common.h"
#include "core/hle/kernel/svc_types.h"
#include "core/hle/result.h"

namespace Common {
class Fiber;
}

namespace Core {
class ARM_Interface;
class System;
} // namespace Core

namespace Kernel {

class GlobalSchedulerContext;
class KernelCore;
class KProcess;
class KScheduler;
class KThreadQueue;

using KThreadFunction = VAddr;

enum class ThreadType : u32 {
    Main = 0,
    Kernel = 1,
    HighPriority = 2,
    User = 3,
    Dummy = 100, // Special thread type for emulation purposes only
};
DECLARE_ENUM_FLAG_OPERATORS(ThreadType);

enum class SuspendType : u32 {
    Process = 0,
    Thread = 1,
    Debug = 2,
    Backtrace = 3,
    Init = 4,

    Count,
};

enum class ThreadState : u16 {
    Initialized = 0,
    Waiting = 1,
    Runnable = 2,
    Terminated = 3,

    SuspendShift = 4,
    Mask = (1 << SuspendShift) - 1,

    ProcessSuspended = (1 << (0 + SuspendShift)),
    ThreadSuspended = (1 << (1 + SuspendShift)),
    DebugSuspended = (1 << (2 + SuspendShift)),
    BacktraceSuspended = (1 << (3 + SuspendShift)),
    InitSuspended = (1 << (4 + SuspendShift)),

    SuspendFlagMask = ((1 << 5) - 1) << SuspendShift,
};
DECLARE_ENUM_FLAG_OPERATORS(ThreadState);

enum class DpcFlag : u32 {
    Terminating = (1 << 0),
    Terminated = (1 << 1),
};

enum class ThreadWaitReasonForDebugging : u32 {
    None,            ///< Thread is not waiting
    Sleep,           ///< Thread is waiting due to a SleepThread SVC
    IPC,             ///< Thread is waiting for the reply from an IPC request
    Synchronization, ///< Thread is waiting due to a WaitSynchronization SVC
    ConditionVar,    ///< Thread is waiting due to a WaitProcessWideKey SVC
    Arbitration,     ///< Thread is waiting due to a SignalToAddress/WaitForAddress SVC
    Suspended,       ///< Thread is waiting due to process suspension
};

enum class StepState : u32 {
    NotStepping,   ///< Thread is not currently stepping
    StepPending,   ///< Thread will step when next scheduled
    StepPerformed, ///< Thread has stepped, waiting to be scheduled again
};

void SetCurrentThread(KernelCore& kernel, KThread* thread);
[[nodiscard]] KThread* GetCurrentThreadPointer(KernelCore& kernel);
[[nodiscard]] KThread& GetCurrentThread(KernelCore& kernel);
[[nodiscard]] KProcess* GetCurrentProcessPointer(KernelCore& kernel);
[[nodiscard]] KProcess& GetCurrentProcess(KernelCore& kernel);
[[nodiscard]] s32 GetCurrentCoreId(KernelCore& kernel);

class KThread final : public KAutoObjectWithSlabHeapAndContainer<KThread, KWorkerTask>,
                      public boost::intrusive::list_base_hook<>,
                      public KTimerTask {
    KERNEL_AUTOOBJECT_TRAITS(KThread, KSynchronizationObject);

private:
    friend class KScheduler;
    friend class KProcess;

public:
    static constexpr s32 DefaultThreadPriority = 44;
    static constexpr s32 IdleThreadPriority = Svc::LowestThreadPriority + 1;
    static constexpr s32 DummyThreadPriority = Svc::LowestThreadPriority + 2;

    explicit KThread(KernelCore& kernel_);
    ~KThread() override;

public:
    using ThreadContext32 = Core::ARM_Interface::ThreadContext32;
    using ThreadContext64 = Core::ARM_Interface::ThreadContext64;
    using WaiterList = boost::intrusive::list<KThread>;

    void SetName(std::string new_name) {
        name = std::move(new_name);
    }

    /**
     * Gets the thread's current priority
     * @return The current thread's priority
     */
    [[nodiscard]] s32 GetPriority() const {
        return priority;
    }

    /**
     * Sets the thread's current priority.
     * @param priority The new priority.
     */
    void SetPriority(s32 value) {
        priority = value;
    }

    /**
     * Gets the thread's nominal priority.
     * @return The current thread's nominal priority.
     */
    [[nodiscard]] s32 GetBasePriority() const {
        return base_priority;
    }

    /**
     * Gets the thread's thread ID
     * @return The thread's ID
     */
    [[nodiscard]] u64 GetThreadID() const {
        return thread_id;
    }

    void ContinueIfHasKernelWaiters() {
        if (GetNumKernelWaiters() > 0) {
            Continue();
        }
    }

    void SetBasePriority(s32 value);

    [[nodiscard]] Result Run();

    void Exit();

    Result Terminate();

    ThreadState RequestTerminate();

    [[nodiscard]] u32 GetSuspendFlags() const {
        return suspend_allowed_flags & suspend_request_flags;
    }

    [[nodiscard]] bool IsSuspended() const {
        return GetSuspendFlags() != 0;
    }

    [[nodiscard]] bool IsSuspendRequested(SuspendType type) const {
        return (suspend_request_flags &
                (1u << (static_cast<u32>(ThreadState::SuspendShift) + static_cast<u32>(type)))) !=
               0;
    }

    [[nodiscard]] bool IsSuspendRequested() const {
        return suspend_request_flags != 0;
    }

    void RequestSuspend(SuspendType type);

    void Resume(SuspendType type);

    void TrySuspend();

    void UpdateState();

    void Continue();

    constexpr void SetSyncedIndex(s32 index) {
        synced_index = index;
    }

    [[nodiscard]] constexpr s32 GetSyncedIndex() const {
        return synced_index;
    }

    constexpr void SetWaitResult(Result wait_res) {
        wait_result = wait_res;
    }

    [[nodiscard]] constexpr Result GetWaitResult() const {
        return wait_result;
    }

    /*
     * Returns the Thread Local Storage address of the current thread
     * @returns VAddr of the thread's TLS
     */
    [[nodiscard]] VAddr GetTLSAddress() const {
        return tls_address;
    }

    /*
     * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
     * @returns The value of the TPIDR_EL0 register.
     */
    [[nodiscard]] u64 GetTPIDR_EL0() const {
        return thread_context_64.tpidr;
    }

    /// Sets the value of the TPIDR_EL0 Read/Write system register for this thread.
    void SetTPIDR_EL0(u64 value) {
        thread_context_64.tpidr = value;
        thread_context_32.tpidr = static_cast<u32>(value);
    }

    void CloneFpuStatus();

    [[nodiscard]] ThreadContext32& GetContext32() {
        return thread_context_32;
    }

    [[nodiscard]] const ThreadContext32& GetContext32() const {
        return thread_context_32;
    }

    [[nodiscard]] ThreadContext64& GetContext64() {
        return thread_context_64;
    }

    [[nodiscard]] const ThreadContext64& GetContext64() const {
        return thread_context_64;
    }

    [[nodiscard]] std::shared_ptr<Common::Fiber>& GetHostContext();

    [[nodiscard]] ThreadState GetState() const {
        return thread_state.load(std::memory_order_relaxed) & ThreadState::Mask;
    }

    [[nodiscard]] ThreadState GetRawState() const {
        return thread_state.load(std::memory_order_relaxed);
    }

    void SetState(ThreadState state);

    [[nodiscard]] StepState GetStepState() const {
        return step_state;
    }

    void SetStepState(StepState state) {
        step_state = state;
    }

    [[nodiscard]] s64 GetLastScheduledTick() const {
        return last_scheduled_tick;
    }

    void SetLastScheduledTick(s64 tick) {
        last_scheduled_tick = tick;
    }

    void AddCpuTime([[maybe_unused]] s32 core_id_, s64 amount) {
        cpu_time += amount;
        // TODO(bunnei): Debug kernels track per-core tick counts. Should we?
    }

    [[nodiscard]] s64 GetCpuTime() const {
        return cpu_time;
    }

    [[nodiscard]] s32 GetActiveCore() const {
        return core_id;
    }

    void SetActiveCore(s32 core) {
        core_id = core;
    }

    [[nodiscard]] s32 GetCurrentCore() const {
        return current_core_id;
    }

    void SetCurrentCore(s32 core) {
        current_core_id = core;
    }

    [[nodiscard]] KProcess* GetOwnerProcess() {
        return parent;
    }

    [[nodiscard]] const KProcess* GetOwnerProcess() const {
        return parent;
    }

    [[nodiscard]] bool IsUserThread() const {
        return parent != nullptr;
    }

    u16 GetUserDisableCount() const;
    void SetInterruptFlag();
    void ClearInterruptFlag();

    KThread* GetLockOwner() const;

    [[nodiscard]] const KAffinityMask& GetAffinityMask() const {
        return physical_affinity_mask;
    }

    [[nodiscard]] Result GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask);

    [[nodiscard]] Result GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask);

    [[nodiscard]] Result SetCoreMask(s32 cpu_core_id, u64 v_affinity_mask);

    [[nodiscard]] Result SetActivity(Svc::ThreadActivity activity);

    [[nodiscard]] Result Sleep(s64 timeout);

    [[nodiscard]] s64 GetYieldScheduleCount() const {
        return schedule_count;
    }

    void SetYieldScheduleCount(s64 count) {
        schedule_count = count;
    }

    void WaitCancel();

    [[nodiscard]] bool IsWaitCancelled() const {
        return wait_cancelled;
    }

    void ClearWaitCancelled() {
        wait_cancelled = false;
    }

    [[nodiscard]] bool IsCancellable() const {
        return cancellable;
    }

    void SetCancellable() {
        cancellable = true;
    }

    void ClearCancellable() {
        cancellable = false;
    }

    [[nodiscard]] bool IsTerminationRequested() const {
        return termination_requested || GetRawState() == ThreadState::Terminated;
    }

    [[nodiscard]] u64 GetId() const override {
        return this->GetThreadID();
    }

    [[nodiscard]] bool IsInitialized() const override {
        return initialized;
    }

    [[nodiscard]] uintptr_t GetPostDestroyArgument() const override {
        return reinterpret_cast<uintptr_t>(parent) | (resource_limit_release_hint ? 1 : 0);
    }

    void Finalize() override;

    [[nodiscard]] bool IsSignaled() const override;

    void OnTimer();

    void DoWorkerTaskImpl();

    static void PostDestroy(uintptr_t arg);

    [[nodiscard]] static Result InitializeDummyThread(KThread* thread, KProcess* owner);

    [[nodiscard]] static Result InitializeMainThread(Core::System& system, KThread* thread,
                                                     s32 virt_core);

    [[nodiscard]] static Result InitializeIdleThread(Core::System& system, KThread* thread,
                                                     s32 virt_core);

    [[nodiscard]] static Result InitializeHighPriorityThread(Core::System& system, KThread* thread,
                                                             KThreadFunction func, uintptr_t arg,
                                                             s32 virt_core);

    [[nodiscard]] static Result InitializeUserThread(Core::System& system, KThread* thread,
                                                     KThreadFunction func, uintptr_t arg,
                                                     VAddr user_stack_top, s32 prio, s32 virt_core,
                                                     KProcess* owner);

    [[nodiscard]] static Result InitializeServiceThread(Core::System& system, KThread* thread,
                                                        std::function<void()>&& thread_func,
                                                        s32 prio, s32 virt_core, KProcess* owner);

public:
    struct StackParameters {
        u8 svc_permission[0x10];
        std::atomic<u8> dpc_flags;
        u8 current_svc_id;
        bool is_calling_svc;
        bool is_in_exception_handler;
        bool is_pinned;
        s32 disable_count;
        KThread* cur_thread;
    };

    [[nodiscard]] StackParameters& GetStackParameters() {
        return stack_parameters;
    }

    [[nodiscard]] const StackParameters& GetStackParameters() const {
        return stack_parameters;
    }

    class QueueEntry {
    public:
        constexpr QueueEntry() = default;

        constexpr void Initialize() {
            prev = nullptr;
            next = nullptr;
        }

        constexpr KThread* GetPrev() const {
            return prev;
        }
        constexpr KThread* GetNext() const {
            return next;
        }
        constexpr void SetPrev(KThread* thread) {
            prev = thread;
        }
        constexpr void SetNext(KThread* thread) {
            next = thread;
        }

    private:
        KThread* prev{};
        KThread* next{};
    };

    [[nodiscard]] QueueEntry& GetPriorityQueueEntry(s32 core) {
        return per_core_priority_queue_entry[core];
    }

    [[nodiscard]] const QueueEntry& GetPriorityQueueEntry(s32 core) const {
        return per_core_priority_queue_entry[core];
    }

    [[nodiscard]] s32 GetDisableDispatchCount() const {
        return this->GetStackParameters().disable_count;
    }

    void DisableDispatch() {
        ASSERT(GetCurrentThread(kernel).GetDisableDispatchCount() >= 0);
        this->GetStackParameters().disable_count++;
    }

    void EnableDispatch() {
        ASSERT(GetCurrentThread(kernel).GetDisableDispatchCount() > 0);
        this->GetStackParameters().disable_count--;
    }

    void Pin(s32 current_core);

    void Unpin();

    void SetInExceptionHandler() {
        this->GetStackParameters().is_in_exception_handler = true;
    }

    void ClearInExceptionHandler() {
        this->GetStackParameters().is_in_exception_handler = false;
    }

    [[nodiscard]] bool IsInExceptionHandler() const {
        return this->GetStackParameters().is_in_exception_handler;
    }

    void SetIsCallingSvc() {
        this->GetStackParameters().is_calling_svc = true;
    }

    void ClearIsCallingSvc() {
        this->GetStackParameters().is_calling_svc = false;
    }

    [[nodiscard]] bool IsCallingSvc() const {
        return this->GetStackParameters().is_calling_svc;
    }

    [[nodiscard]] u8 GetSvcId() const {
        return this->GetStackParameters().current_svc_id;
    }

    void RegisterDpc(DpcFlag flag) {
        this->GetStackParameters().dpc_flags |= static_cast<u8>(flag);
    }

    void ClearDpc(DpcFlag flag) {
        this->GetStackParameters().dpc_flags &= ~static_cast<u8>(flag);
    }

    [[nodiscard]] u8 GetDpc() const {
        return this->GetStackParameters().dpc_flags;
    }

    [[nodiscard]] bool HasDpc() const {
        return this->GetDpc() != 0;
    }

    void SetWaitReasonForDebugging(ThreadWaitReasonForDebugging reason) {
        wait_reason_for_debugging = reason;
    }

    [[nodiscard]] ThreadWaitReasonForDebugging GetWaitReasonForDebugging() const {
        return wait_reason_for_debugging;
    }

    [[nodiscard]] ThreadType GetThreadType() const {
        return thread_type;
    }

    [[nodiscard]] bool IsDummyThread() const {
        return GetThreadType() == ThreadType::Dummy;
    }

    void SetWaitObjectsForDebugging(const std::span<KSynchronizationObject*>& objects) {
        wait_objects_for_debugging.clear();
        wait_objects_for_debugging.reserve(objects.size());
        for (const auto& object : objects) {
            wait_objects_for_debugging.emplace_back(object);
        }
    }

    [[nodiscard]] const std::vector<KSynchronizationObject*>& GetWaitObjectsForDebugging() const {
        return wait_objects_for_debugging;
    }

    void SetMutexWaitAddressForDebugging(VAddr address) {
        mutex_wait_address_for_debugging = address;
    }

    [[nodiscard]] VAddr GetMutexWaitAddressForDebugging() const {
        return mutex_wait_address_for_debugging;
    }

    [[nodiscard]] s32 GetIdealCoreForDebugging() const {
        return virtual_ideal_core_id;
    }

    void AddWaiter(KThread* thread);

    void RemoveWaiter(KThread* thread);

    [[nodiscard]] Result GetThreadContext3(std::vector<u8>& out);

    [[nodiscard]] KThread* RemoveUserWaiterByKey(bool* out_has_waiters, VAddr key) {
        return this->RemoveWaiterByKey(out_has_waiters, key, false);
    }

    [[nodiscard]] KThread* RemoveKernelWaiterByKey(bool* out_has_waiters, VAddr key) {
        return this->RemoveWaiterByKey(out_has_waiters, key, true);
    }

    [[nodiscard]] VAddr GetAddressKey() const {
        return address_key;
    }

    [[nodiscard]] u32 GetAddressKeyValue() const {
        return address_key_value;
    }

    [[nodiscard]] bool GetIsKernelAddressKey() const {
        return is_kernel_address_key;
    }

    //! NB: intentional deviation from official kernel.
    //
    // Separate SetAddressKey into user and kernel versions
    // to cope with arbitrary host pointers making their way
    // into things.

    void SetUserAddressKey(VAddr key, u32 val) {
        ASSERT(waiting_lock_info == nullptr);
        address_key = key;
        address_key_value = val;
        is_kernel_address_key = false;
    }

    void SetKernelAddressKey(VAddr key) {
        ASSERT(waiting_lock_info == nullptr);
        address_key = key;
        is_kernel_address_key = true;
    }

    void ClearWaitQueue() {
        wait_queue = nullptr;
    }

    void BeginWait(KThreadQueue* queue);
    void NotifyAvailable(KSynchronizationObject* signaled_object, Result wait_result_);
    void EndWait(Result wait_result_);
    void CancelWait(Result wait_result_, bool cancel_timer_task);

    [[nodiscard]] s32 GetNumKernelWaiters() const {
        return num_kernel_waiters;
    }

    [[nodiscard]] u64 GetConditionVariableKey() const {
        return condvar_key;
    }

    [[nodiscard]] u64 GetAddressArbiterKey() const {
        return condvar_key;
    }

    // Dummy threads (used for HLE host threads) cannot wait based on the guest scheduler, and
    // therefore will not block on guest kernel synchronization primitives. These methods handle
    // blocking as needed.

    void RequestDummyThreadWait();
    void DummyThreadBeginWait();
    void DummyThreadEndWait();

    [[nodiscard]] uintptr_t GetArgument() const {
        return argument;
    }

    [[nodiscard]] VAddr GetUserStackTop() const {
        return stack_top;
    }

private:
    [[nodiscard]] KThread* RemoveWaiterByKey(bool* out_has_waiters, VAddr key,
                                             bool is_kernel_address_key);

    static constexpr size_t PriorityInheritanceCountMax = 10;
    union SyncObjectBuffer {
        std::array<KSynchronizationObject*, Svc::ArgumentHandleCountMax> sync_objects{};
        std::array<Handle,
                   Svc::ArgumentHandleCountMax * (sizeof(KSynchronizationObject*) / sizeof(Handle))>
            handles;
        constexpr SyncObjectBuffer() {}
    };
    static_assert(sizeof(SyncObjectBuffer::sync_objects) == sizeof(SyncObjectBuffer::handles));

    struct ConditionVariableComparator {
        struct RedBlackKeyType {
            u64 cv_key{};
            s32 priority{};

            [[nodiscard]] constexpr u64 GetConditionVariableKey() const {
                return cv_key;
            }

            [[nodiscard]] constexpr s32 GetPriority() const {
                return priority;
            }
        };

        template <typename T>
            requires(std::same_as<T, KThread> || std::same_as<T, RedBlackKeyType>)
        static constexpr int Compare(const T& lhs, const KThread& rhs) {
            const u64 l_key = lhs.GetConditionVariableKey();
            const u64 r_key = rhs.GetConditionVariableKey();

            if (l_key < r_key) {
                // Sort first by key
                return -1;
            } else if (l_key == r_key && lhs.GetPriority() < rhs.GetPriority()) {
                // And then by priority.
                return -1;
            } else {
                return 1;
            }
        }
    };

    void AddWaiterImpl(KThread* thread);
    void RemoveWaiterImpl(KThread* thread);
    static void RestorePriority(KernelCore& kernel, KThread* thread);

    void StartTermination();
    void FinishTermination();

    void IncreaseBasePriority(s32 priority);

    [[nodiscard]] Result Initialize(KThreadFunction func, uintptr_t arg, VAddr user_stack_top,
                                    s32 prio, s32 virt_core, KProcess* owner, ThreadType type);

    [[nodiscard]] static Result InitializeThread(KThread* thread, KThreadFunction func,
                                                 uintptr_t arg, VAddr user_stack_top, s32 prio,
                                                 s32 core, KProcess* owner, ThreadType type,
                                                 std::function<void()>&& init_func);

    // For core KThread implementation
    ThreadContext32 thread_context_32{};
    ThreadContext64 thread_context_64{};
    Common::IntrusiveRedBlackTreeNode condvar_arbiter_tree_node{};
    s32 priority{};
    using ConditionVariableThreadTreeTraits =
        Common::IntrusiveRedBlackTreeMemberTraitsDeferredAssert<
            &KThread::condvar_arbiter_tree_node>;
    using ConditionVariableThreadTree =
        ConditionVariableThreadTreeTraits::TreeType<ConditionVariableComparator>;

private:
    struct LockWithPriorityInheritanceComparator {
        struct RedBlackKeyType {
            s32 m_priority;

            constexpr s32 GetPriority() const {
                return m_priority;
            }
        };

        template <typename T>
            requires(std::same_as<T, KThread> || std::same_as<T, RedBlackKeyType>)
        static constexpr int Compare(const T& lhs, const KThread& rhs) {
            if (lhs.GetPriority() < rhs.GetPriority()) {
                // Sort by priority.
                return -1;
            } else {
                return 1;
            }
        }
    };
    static_assert(std::same_as<Common::RedBlackKeyType<LockWithPriorityInheritanceComparator, void>,
                               LockWithPriorityInheritanceComparator::RedBlackKeyType>);

    using LockWithPriorityInheritanceThreadTreeTraits =
        Common::IntrusiveRedBlackTreeMemberTraitsDeferredAssert<
            &KThread::condvar_arbiter_tree_node>;
    using LockWithPriorityInheritanceThreadTree =
        ConditionVariableThreadTreeTraits::TreeType<LockWithPriorityInheritanceComparator>;

public:
    class LockWithPriorityInheritanceInfo : public KSlabAllocated<LockWithPriorityInheritanceInfo>,
                                            public boost::intrusive::list_base_hook<> {
    public:
        explicit LockWithPriorityInheritanceInfo(KernelCore&) {}

        static LockWithPriorityInheritanceInfo* Create(KernelCore& kernel, VAddr address_key,
                                                       bool is_kernel_address_key) {
            // Create a new lock info.
            auto* new_lock = LockWithPriorityInheritanceInfo::Allocate(kernel);
            ASSERT(new_lock != nullptr);

            // Set the new lock's address key.
            new_lock->m_address_key = address_key;
            new_lock->m_is_kernel_address_key = is_kernel_address_key;

            return new_lock;
        }

        void SetOwner(KThread* new_owner) {
            // Set new owner.
            m_owner = new_owner;
        }

        void AddWaiter(KThread* waiter) {
            // Insert the waiter.
            m_tree.insert(*waiter);
            m_waiter_count++;

            waiter->SetWaitingLockInfo(this);
        }

        [[nodiscard]] bool RemoveWaiter(KThread* waiter) {
            m_tree.erase(m_tree.iterator_to(*waiter));

            waiter->SetWaitingLockInfo(nullptr);

            return (--m_waiter_count) == 0;
        }

        KThread* GetHighestPriorityWaiter() {
            return std::addressof(m_tree.front());
        }
        const KThread* GetHighestPriorityWaiter() const {
            return std::addressof(m_tree.front());
        }

        LockWithPriorityInheritanceThreadTree& GetThreadTree() {
            return m_tree;
        }
        const LockWithPriorityInheritanceThreadTree& GetThreadTree() const {
            return m_tree;
        }

        VAddr GetAddressKey() const {
            return m_address_key;
        }
        bool GetIsKernelAddressKey() const {
            return m_is_kernel_address_key;
        }
        KThread* GetOwner() const {
            return m_owner;
        }
        u32 GetWaiterCount() const {
            return m_waiter_count;
        }

    private:
        LockWithPriorityInheritanceThreadTree m_tree{};
        VAddr m_address_key{};
        KThread* m_owner{};
        u32 m_waiter_count{};
        bool m_is_kernel_address_key{};
    };

    void SetWaitingLockInfo(LockWithPriorityInheritanceInfo* lock) {
        waiting_lock_info = lock;
    }

    LockWithPriorityInheritanceInfo* GetWaitingLockInfo() {
        return waiting_lock_info;
    }

    void AddHeldLock(LockWithPriorityInheritanceInfo* lock_info);
    LockWithPriorityInheritanceInfo* FindHeldLock(VAddr address_key, bool is_kernel_address_key);

private:
    using LockWithPriorityInheritanceInfoList =
        boost::intrusive::list<LockWithPriorityInheritanceInfo>;

    ConditionVariableThreadTree* condvar_tree{};
    u64 condvar_key{};
    u64 virtual_affinity_mask{};
    KAffinityMask physical_affinity_mask{};
    u64 thread_id{};
    std::atomic<s64> cpu_time{};
    VAddr address_key{};
    KProcess* parent{};
    VAddr kernel_stack_top{};
    u32* light_ipc_data{};
    VAddr tls_address{};
    KLightLock activity_pause_lock;
    s64 schedule_count{};
    s64 last_scheduled_tick{};
    std::array<QueueEntry, Core::Hardware::NUM_CPU_CORES> per_core_priority_queue_entry{};
    KThreadQueue* wait_queue{};
    LockWithPriorityInheritanceInfoList held_lock_info_list{};
    LockWithPriorityInheritanceInfo* waiting_lock_info{};
    WaiterList pinned_waiter_list{};
    u32 address_key_value{};
    u32 suspend_request_flags{};
    u32 suspend_allowed_flags{};
    s32 synced_index{};
    Result wait_result{ResultSuccess};
    s32 base_priority{};
    s32 physical_ideal_core_id{};
    s32 virtual_ideal_core_id{};
    s32 num_kernel_waiters{};
    s32 current_core_id{};
    s32 core_id{};
    KAffinityMask original_physical_affinity_mask{};
    s32 original_physical_ideal_core_id{};
    s32 num_core_migration_disables{};
    std::atomic<ThreadState> thread_state{};
    std::atomic<bool> termination_requested{};
    bool wait_cancelled{};
    bool cancellable{};
    bool signaled{};
    bool initialized{};
    bool debug_attached{};
    s8 priority_inheritance_count{};
    bool resource_limit_release_hint{};
    bool is_kernel_address_key{};
    StackParameters stack_parameters{};
    Common::SpinLock context_guard{};

    // For emulation
    std::shared_ptr<Common::Fiber> host_context{};
    bool is_single_core{};
    ThreadType thread_type{};
    StepState step_state{};
    std::atomic<bool> dummy_thread_runnable{true};

    // For debugging
    std::vector<KSynchronizationObject*> wait_objects_for_debugging;
    VAddr mutex_wait_address_for_debugging{};
    ThreadWaitReasonForDebugging wait_reason_for_debugging{};
    uintptr_t argument{};
    VAddr stack_top{};
    std::string name{};

public:
    using ConditionVariableThreadTreeType = ConditionVariableThreadTree;

    void SetConditionVariable(ConditionVariableThreadTree* tree, VAddr address, u64 cv_key,
                              u32 value) {
        ASSERT(waiting_lock_info == nullptr);
        condvar_tree = tree;
        condvar_key = cv_key;
        address_key = address;
        address_key_value = value;
        is_kernel_address_key = false;
    }

    void ClearConditionVariable() {
        condvar_tree = nullptr;
    }

    [[nodiscard]] bool IsWaitingForConditionVariable() const {
        return condvar_tree != nullptr;
    }

    void SetAddressArbiter(ConditionVariableThreadTree* tree, u64 address) {
        ASSERT(waiting_lock_info == nullptr);
        condvar_tree = tree;
        condvar_key = address;
    }

    void ClearAddressArbiter() {
        condvar_tree = nullptr;
    }

    [[nodiscard]] bool IsWaitingForAddressArbiter() const {
        return condvar_tree != nullptr;
    }

    [[nodiscard]] ConditionVariableThreadTree* GetConditionVariableTree() const {
        return condvar_tree;
    }
};

class KScopedDisableDispatch {
public:
    [[nodiscard]] explicit KScopedDisableDispatch(KernelCore& kernel_) : kernel{kernel_} {
        // If we are shutting down the kernel, none of this is relevant anymore.
        if (kernel.IsShuttingDown()) {
            return;
        }
        GetCurrentThread(kernel).DisableDispatch();
    }

    ~KScopedDisableDispatch();

private:
    KernelCore& kernel;
};

inline void KTimerTask::OnTimer() {
    static_cast<KThread*>(this)->OnTimer();
}

} // namespace Kernel